<template>
	<view class="app-layout">
		<!-- 顶部导航栏 -->
		<view class="topbar">
			<div class="topbar-left">
			<view class="back-btn" @click="goBack">
				<image src="/static/fanhui.png" class="back-icon"></image>
			</view>
			<image class="logo" src="/static/logo_2.0.jpg"></image>
			<text class="brand">旭荣网盾(GDCS)</text>
		</div>
			<view class="topbar-center">
				<text class="page-title">用户管理</text>
			</view>
			<view class="topbar-right">
					<image class="icon" src="/static/Notice.png"></image>
					<image class="avatar" :src="currentAvatar" />
				</view>
		</view>



		<view class="content">
			<!-- 右侧主区域 -->
			<view class="main">
				<view class="user-management">
					<!-- 搜索和操作栏 -->
					<view class="action-bar">
						<view class="search-box">
							<input class="search-input" v-model="searchKeyword" placeholder="搜索用户名或邮箱" />
						</view>
						<button class="add-btn" @click="showAddUser = true">添加用户</button>
					</view>

					<!-- 用户列表 -->
					<view class="user-list">
						<view class="table-header">
							<view class="col-id">ID</view>
							<view class="col-name">用户名</view>
							<view class="col-email">邮箱</view>
							<view class="col-role">角色</view>
							<view class="col-time">注册时间</view>
							<view class="col-actions">操作</view>
						</view>
						<scroll-view class="table-body" scroll-y>
							<view class="user-row" v-for="user in filteredUsers" :key="user.id">
								<view class="col-id">{{ user.id }}</view>
								<view class="col-name">{{ user.user_name }}</view>
								<view class="col-email">{{ user.email }}</view>
								<view class="col-role">
							<text :class="['role-tag', user.role]">{{ user.role === 'admin' ? '管理员' : '普通用户' }}</text>
						</view>
								<view class="col-time">{{ user.registerTime }}</view>
								<view class="col-actions">
							<button class="edit-btn" @click="editUser(user)">编辑</button>
							<button class="delete-btn" @click="deleteUser(user)">删除</button>
						</view>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加/编辑用户弹窗 -->
		<view class="modal" v-if="showAddUser || showEditUser">
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">{{ showAddUser ? '添加用户' : '编辑用户' }}</text>
					<view class="close-btn" @click="closeModal">×</view>
				</view>
				<view class="modal-body">
					<view class="form-group">
						<label>用户名</label>
						<input v-model="currentUser.user_name" placeholder="请输入用户名" />
					</view>
					<view class="form-group">
						<label>邮箱</label>
						<input v-model="currentUser.email" placeholder="请输入邮箱" />
					</view>
					<view class="form-group">
						<label>密码</label>
						<input v-model="currentUser.password" type="password" placeholder="请输入密码" />
					</view>
					<view class="form-group">
						<label>角色</label>
						<view class="radio-group">
							<label class="radio-item">
								<input type="radio" v-model="currentUser.role" value="user" />
								<span>普通用户</span>
							</label>
							<label class="radio-item">
								<input type="radio" v-model="currentUser.role" value="admin" />
								<span>管理员</span>
							</label>
						</view>
					</view>
				</view>
				<view class="modal-footer">
							<button class="cancel-btn" @click="closeModal">取消</button>
							<button class="confirm-btn" @click="saveUser">{{ showAddUser ? '添加' : '保存' }}</button>
						</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getUsers, deleteUser, updateUser } from '../../api/api.js'

export default {
	data() {
		return {
		searchKeyword: '',
		showAddUser: false,
		showEditUser: false,
		currentAvatar: uni.getStorageSync('currentAvatar') || '/static/touxiang01.webp',
		currentUser: {
			id: null,
			user_name: '',
			email: '',
			password: '',
			role: 'user'
		},
		users: []
	}
	},
	computed: {
		filteredUsers() {
			if (!this.searchKeyword) {
				return this.users;
			}
			const keyword = this.searchKeyword.toLowerCase();
			return this.users.filter(user => 
				user.user_name.toLowerCase().includes(keyword) ||
				user.email.toLowerCase().includes(keyword)
			);
		}
	},
	mounted() {
			// 页面加载时检查管理员权限
			if (!this.checkAdminPermission()) {
				return;
			}
			// 页面加载时初始化用户信息
			this.initUserInfo();
			
			// 监听本地存储变化，实时更新头像
			uni.$on('avatarChanged', (avatar) => {
				this.currentAvatar = avatar;
			});
		},
	methods: {
		// 检查管理员权限
		checkAdminPermission() {
			// 从本地存储获取当前登录用户信息
			const currentUser = uni.getStorageSync('currentUser');
			if (!currentUser || currentUser.user_id !== 0) {
				uni.showModal({
					title: '权限不足',
					content: '只有管理员才能访问用户管理页面',
					showCancel: false,
					success: () => {
						uni.navigateBack();
					}
				});
				return false;
			}
			return true;
		},
		editUser(user) {
			this.currentUser = { ...user };
			this.showEditUser = true;
		},
		async deleteUser(user) {
			uni.showModal({
				title: '确认删除',
				content: `确定要删除用户 "${user.user_name}" 吗？`,
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await deleteUser(user.id);
							if (result.success) {
								const index = this.users.findIndex(u => u.id === user.id);
								if (index !== -1) {
									this.users.splice(index, 1);
								}
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: result.message || '删除用户失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('删除用户失败:', error);
							uni.showToast({
								title: '删除用户失败，请重试',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		closeModal() {
			this.showAddUser = false;
			this.showEditUser = false;
			this.currentUser = {
				id: null,
				user_name: '',
				email: '',
				password: '',
				role: 'user'
			};
		},
		async saveUser() {
			if (!this.currentUser.user_name || !this.currentUser.email) {
				uni.showToast({
					title: '请填写完整信息',
					icon: 'none'
				});
				return;
			}

			try {
				if (this.showAddUser) {
					// 添加新用户
					const newUser = {
						id: Math.max(...this.users.map(u => u.id)) + 1,
						user_name: this.currentUser.user_name,
						email: this.currentUser.email,
						role: this.currentUser.role,
						registerTime: new Date().toLocaleString('zh-CN')
					};
					this.users.push(newUser);
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
				} else {
					// 编辑用户
					const result = await updateUser(this.currentUser.id, this.currentUser.user_name, this.currentUser.email);
					if (result.success) {
						const index = this.users.findIndex(u => u.id === this.currentUser.id);
						if (index !== -1) {
							this.users[index] = { ...this.currentUser };
						}
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: result.message || '更新用户信息失败',
							icon: 'none'
						});
						return;
					}
				}

				this.closeModal();
			} catch (error) {
				console.error('保存用户失败:', error);
				uni.showToast({
					title: '保存用户失败，请重试',
					icon: 'none'
				});
			}
		},
		initUserInfo() {
			// 从本地存储获取用户信息
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo && userInfo.user_name) {
				// 更新左侧边栏显示的用户名
				const adminUser = this.users.find(user => user.id === 1);
				if (adminUser) {
					adminUser.user_name = userInfo.user_name;
				}
			}
			
			// 从本地存储获取用户头像
			const userAvatar = uni.getStorageSync('userAvatar');
			if (userAvatar) {
				this.currentAvatar = userAvatar;
			}
			
			// 获取用户列表
			this.getUsers();
		},
		getUsers() {
			getUsers()
				.then((res) => {
					if (res.success) {
						this.users = res.users;
					} else {
						uni.showToast({
							title: res.message || '获取用户列表失败',
							icon: 'none'
						});
					}
				})
				.catch((err) => {
					console.error('获取用户列表失败:', err);
					uni.showToast({
						title: '获取用户列表失败，请检查网络连接',
						icon: 'none'
					});
				});
		},

		// 返回上一页
		goBack() {
			uni.navigateBack()
		},

		navigateTo(page) {
			if (page === 'home') {
				uni.navigateTo({ url: '/pages/home/home' })
			} else if (page === 'history') {
				uni.navigateTo({ url: '/pages/history/history' })
			} else if (page === 'knowledge') {
				uni.navigateTo({ url: '/pages/knowledge/knowledge' })
			} else if (page === 'users') {
				uni.navigateTo({ url: '/pages/users/users' })
			} else if (page === 'settings') {
				uni.navigateTo({ url: '/pages/settings/settings' })
			}
		}
	}
}
</script>

<style>
	/* 布局 */
	.app-layout {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f6fa;
	}
	.topbar {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.15);
		color: white;
	}
	.topbar-left { display: flex; align-items: center; }
	.back-btn { display: flex; align-items: center; margin-right: 24rpx; cursor: pointer; }
	.back-icon { width: 44rpx; height: 44rpx; }
	.logo { width: 64rpx; height: 64rpx; border-radius: 16rpx; margin-right: 16rpx; border: 2rpx solid rgba(255,255,255,0.2); }
	.brand { font-weight: 700; color: white; font-size: 32rpx; letter-spacing: 1rpx; }
	.topbar-center .page-title { font-size: 36rpx; color: white; font-weight: 600; }
	.topbar-right { display: flex; align-items: center; }
	.icon { width: 48rpx; height: 48rpx; margin-right: 24rpx; opacity: .9; filter: brightness(0) invert(1); }
	.avatar { width: 48rpx; height: 48rpx; border-radius: 50%; background: rgba(255,255,255,0.2); color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; border: 2rpx solid rgba(255,255,255,0.3); }
	.avatar.lg { width: 80rpx; height: 80rpx; font-size: 36rpx; }

	.content { flex: 1; padding: 24rpx; background: #f8fafc; }
	


	.main { flex: 1; }
	.user-management {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
		border: 1rpx solid #e2e8f0;
	}
	.action-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f1f5f9;
	}
	.search-box {
		flex: 1;
		margin-right: 24rpx;
	}
	.search-input {
		width: 100%;
		padding: 16rpx 24rpx;
		border: 2rpx solid #e2e8f0;
		border-radius: 10rpx;
		font-size: 26rpx;
		background: #ffffff;
		transition: all 0.2s ease;
	}
	.search-input:focus {
		border-color: #667eea;
		box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
		outline: none;
	}
	.add-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		border: none;
		padding: 16rpx 32rpx;
		border-radius: 10rpx;
		font-size: 26rpx;
		font-weight: 600;
		box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
		transition: all 0.2s ease;
	}
	.add-btn:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.4);
	}
	.user-list {
		border: 2rpx solid #e2e8f0;
		border-radius: 12rpx;
		overflow: hidden;
		background: #ffffff;
	}
	.table-header {
		display: flex;
		background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
		border-bottom: 2rpx solid #e2e8f0;
		font-weight: 600;
		color: #334155;
		font-size: 26rpx;
		padding: 20rpx 0;
	}
	.table-body {
		max-height: 600rpx;
	}
	.user-row {
		display: flex;
		border-bottom: 1rpx solid #f1f5f9;
		padding: 20rpx 0;
		align-items: center;
		transition: background-color 0.2s ease;
	}
	.user-row:hover {
		background: #f8fafc;
	}
	.user-row:last-child {
		border-bottom: none;
	}
	.col-id { width: 100rpx; text-align: center; }
	.col-name { width: 200rpx; padding-left: 20rpx; }
	.col-email { flex: 1; padding-left: 20rpx; }
	.col-role { width: 150rpx; padding-left: 20rpx; }
	.col-time { width: 200rpx; padding-left: 20rpx; }
	.col-actions { width: 200rpx; display: flex; gap: 10rpx; justify-content: center; }
	.role-tag {
		padding: 6rpx 16rpx;
		border-radius: 16rpx;
		font-size: 22rpx;
		font-weight: 600;
		border: 1rpx solid transparent;
	}
	.role-tag.admin { 
		background: linear-gradient(135deg, #eef1ff 0%, #e0e7ff 100%); 
		color: #4f5bd5; 
		border-color: #c7d2fe;
	}
	.role-tag.user { 
		background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); 
		color: #0ea5e9; 
		border-color: #bae6fd;
	}
	.edit-btn, .delete-btn {
		padding: 10rpx 16rpx;
		border: none;
		border-radius: 6rpx;
		font-size: 22rpx;
		font-weight: 600;
		transition: all 0.2s ease;
		cursor: pointer;
	}
	.edit-btn { 
		background: linear-gradient(135deg, #eef1ff 0%, #e0e7ff 100%); 
		color: #4f5bd5; 
		border: 1rpx solid #c7d2fe;
	}
	.edit-btn:hover {
		background: linear-gradient(135deg, #e0e7ff 0%, #d4dbfe 100%);
		transform: translateY(-1rpx);
	}
	.delete-btn { 
		background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); 
		color: #dc2626; 
		border: 1rpx solid #fca5a5;
	}
	.delete-btn:hover {
		background: linear-gradient(135deg, #fecaca 0%, #fca5a5 100%);
		transform: translateY(-1rpx);
	}

	/* 弹窗样式 */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0,0,0,0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}
	.modal-content {
		background: white;
		border-radius: 12rpx;
		width: 500rpx;
		max-width: 90vw;
		box-shadow: 0 16rpx 48rpx rgba(0,0,0,0.2);
	}
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-bottom: 2rpx solid #e1e5e9;
	}
	.modal-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}
	.close-btn {
		font-size: 40rpx;
		color: #888;
		cursor: pointer;
	}
	.modal-body {
		padding: 20rpx;
	}
	.form-group {
		margin-bottom: 24rpx;
	}
	.form-group label {
		display: block;
		margin-bottom: 8rpx;
		font-size: 26rpx;
		color: #333;
		font-weight: 600;
	}
	.form-group input {
		width: 85%;
		padding: 16rpx 20rpx;
		border: 2rpx solid #e1e5e9;
		border-radius: 8rpx;
		font-size: 28rpx;
		background: #f8f9fa;
	}
	.radio-group {
		display: flex;
		gap: 24rpx;
		margin-top: 8rpx;
	}
	.radio-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		font-size: 26rpx;
		color: #333;
	}
	.modal-footer {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
		padding: 24rpx;
		border-top: 2rpx solid #e1e5e9;
	}
	.cancel-btn, .confirm-btn {
		padding: 16rpx 32rpx;
		border: none;
		border-radius: 10rpx;
		font-size: 26rpx;
		font-weight: 600;
		transition: all 0.2s ease;
		cursor: pointer;
	}
	.cancel-btn {
		background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
		color: #64748b;
		border: 1rpx solid #e2e8f0;
	}
	.cancel-btn:hover {
		background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
		transform: translateY(-1rpx);
	}
	.confirm-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
	}
	.confirm-btn:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.4);
	}
</style>
